package com.am.server.api.system.dictionary.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.am.server.api.system.dictionary.constant.DictionaryLogConstant;
import com.am.server.api.system.dictionary.model.dto.DictionaryItemDto;
import com.am.server.api.system.dictionary.model.dto.DictionaryItemListQueryDto;
import com.am.server.api.system.dictionary.model.dto.SaveDictionaryItemDto;
import com.am.server.api.system.dictionary.model.dto.UpdateDictionaryItemDto;
import com.am.server.api.system.dictionary.service.DictionaryItemService;
import com.am.server.api.system.log.aspect.annotation.WriteLog;
import com.am.server.common.base.model.dto.ResponseMessageDto;
import com.am.server.common.constant.Constant;
import com.am.server.common.constant.MessageConstant;
import com.am.server.common.util.ResponseUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * 字典项管理
 *
 * @author 阮雪峰
 */
@SaCheckLogin
@WriteLog(DictionaryLogConstant.MENU_NAME)
@RestController
@RequestMapping(Constant.ADMIN_ROOT + "/dictionary/item")
public class DictionaryItemController {
    private final DictionaryItemService dictionaryItemService;

    public DictionaryItemController(DictionaryItemService dictionaryItemService) {
        this.dictionaryItemService = dictionaryItemService;
    }

    /**
     * 查询
     *
     * @param dto dto
     * @return org.springframework.http.ResponseEntity
     */
    @GetMapping("/find")
    public ResponseEntity<List<DictionaryItemDto>> find(DictionaryItemListQueryDto dto) {
        return ResponseUtils.ok(dictionaryItemService.find(dto));
    }

    /**
     * 新增
     *
     * @param dto dto
     * @return ResponseEntity
     */
    @WriteLog("新增")
    @PostMapping("/save")
    public ResponseEntity<ResponseMessageDto> save(@Validated @RequestBody SaveDictionaryItemDto dto) {
        dictionaryItemService.save(dto);
        return ResponseUtils.ok(MessageConstant.SAVE_SUCCESS);
    }

    /**
     * 修改
     *
     * @param dto dto
     * @return ResponseEntity
     */
    @WriteLog("修改")
    @PostMapping("/update")
    public ResponseEntity<ResponseMessageDto> update(@Validated @RequestBody UpdateDictionaryItemDto dto) {
        dictionaryItemService.update(dto);
        return ResponseUtils.ok(MessageConstant.UPDATE_SUCCESS);
    }

    /**
     * 删除
     *
     * @param id 主键
     * @return ResponseEntity
     */
    @WriteLog("删除")
    @DeleteMapping("/delete")
    public ResponseEntity<ResponseMessageDto> delete(Long id) {
        return Optional.ofNullable(id)
                .map(i -> {
                    dictionaryItemService.delete(id);
                    return ResponseUtils.ok(MessageConstant.DELETE_SUCCESS);
                })
                .orElse(ResponseUtils.ok(MessageConstant.COMMON_DELETE_PRIMARY_KEY_NULL));
    }
}
